package com.heima.admin.gateway.filter;

import com.heima.model.admin.pojos.AdUser;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.Payload;
import com.heima.utils.common.RsaUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PublicKey;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Value("${leadnews.jwt.publicKeyPath}")
    private String publicKeyPath;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求和响应

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.对登录请求直接放行
        //1）取出当前请求URI

        String uri = request.getURI().getPath();
        if (uri.contains("/login/in")) {
            return chain.filter(exchange);
        }
        //3.从请求头中取出token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.使用Jwt工具+RSA公钥校验token合法性


        try {
            PublicKey publicKey = RsaUtils.getPublicKey(publicKeyPath);
            Payload<AdUser> payload = JwtUtils.getInfoFromToken(token, publicKey, AdUser.class);

            AdUser adUser = payload.getInfo();
            request.mutate().header("userId", adUser.getId() + "");
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);


    }

    @Override
    public int getOrder() {
        /**
         * 返回数值，数值越大，优先级越小
         * @return
         */
        return 0;
    }
}
